package com.like.hospitalworld;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import com.like.entity.Department;
import com.like.entity.GeneralResponse;
import com.like.entity.GetDepReq;
import com.like.entity.GetDepResp;
import com.like.entity.LoginReq;
import com.like.entity.LoginResp;
import com.like.likeutils.network.RetrofitCallback;
import com.like.network.AuthService;
import com.like.network.ResponseCode;
import com.like.network.RetrofitUtil;
import com.like.network.UserService;
import com.like.utils.Constants;
import com.like.widget.MyToast;
import com.mobsandgeeks.saripaar.ValidationError;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.annotation.NotEmpty;
import com.mobsandgeeks.saripaar.annotation.Order;
import com.mobsandgeeks.saripaar.annotation.Pattern;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.List;

import retrofit2.Call;
import retrofit2.Response;

@ContentView(R.layout.activity_login)
public class LoginActivity extends BaseActivity implements Validator.ValidationListener {

    @ViewInject(R.id.mobile_no)
    @Order(0)
    @Pattern(regex = "^[1]([3][0-9]{1}|59|58|88|89)[0-9]{8}$", message = "手机号输入错误")
    private EditText mMobileNo;
    @ViewInject(R.id.pwd)
    @Order(1)
    @NotEmpty(message = "请输入密码")
    private EditText mPwd;

    private AuthService mAuthService;
    private UserService mUserService;
    private int mAllDepCounts = 0;
    private int mCurrentDepCount = 0;
    private Department mRootDep;
    private Validator mValidator;
    private boolean mIsPass = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAuthService = RetrofitUtil.getService(AuthService.class);
        mUserService = RetrofitUtil.getService(UserService.class);
        mValidator = new Validator(this);
        mValidator.setValidationListener(this);
    }

    @Event(R.id.back)
    private void backClick(View v) {
        this.finish();
    }

    @Event(R.id.btn_reg)
    private void regClick(View v) {
        Intent intent = new Intent(m.mContext, RegActivity.class);
        startActivity(intent);
        finish();
    }

    @Event(R.id.login)
    private void loginClick(View v) {
        mValidator.validate();
        if (!mIsPass)
            return;
        String mobile = mMobileNo.getText().toString();
        String pwd = mPwd.getText().toString();
        String address = m.getLatitude() + "#" + m.getLongitude();
        LoginReq req = new LoginReq(mobile, "", pwd, address);
        Call<GeneralResponse<LoginResp>> call = mAuthService.login(Constants.getGUID(), m.getToken(), req);
        call.enqueue(new RetrofitCallback<GeneralResponse<LoginResp>>() {
            @Override
            public void onResponse(Call<GeneralResponse<LoginResp>> call, Response<GeneralResponse<LoginResp>> response) {
                if (!response.isSuccessful())
                    return;
                LoginResp resp = response.body().data;
                if (resp.result == ResponseCode.SUCCESS) {
                    MyToast.showBlueCircleToast(m.mContext, "登陆成功");
                    m.setLoginResp(resp);
                    Intent intent = new Intent(m.mContext, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else
                    MyToast.showBlueCircleToast(m.mContext, "用户名或密码错误");
            }

            @Override
            public void onFailure(Call<GeneralResponse<LoginResp>> call, Throwable t) {
            }
        });
    }

    private void getAllDepartments() {
        if (m.getToken() == null)
            return;
        GetDepReq req = new GetDepReq(GetDepReq.DEP_ALL);
        Call<GeneralResponse<GetDepResp>> call = mUserService.getDepartmentList(Constants.getGUID(), m.getToken(), req);
        call.enqueue(new RetrofitCallback<GeneralResponse<GetDepResp>>() {
            @Override
            public void onResponse(Call<GeneralResponse<GetDepResp>> call, Response<GeneralResponse<GetDepResp>> response) {
                if (!response.isSuccessful())
                    return;
                GeneralResponse<GetDepResp> resp = response.body();
                GetDepResp getDepResp = resp.data;
                List<Department> deps = getDepResp.departments;
                mAllDepCounts = deps.size();
                getDepartments(GetDepReq.DEP_MAIN, mRootDep);
            }

            @Override
            public void onFailure(Call<GeneralResponse<GetDepResp>> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    private void getDepartments(int depId, final Department parentDep) {
        GetDepReq req = new GetDepReq(depId);
        Call<GeneralResponse<GetDepResp>> call = mUserService.getDepartmentList(Constants.getGUID(), m.getToken(), req);
        call.enqueue(new RetrofitCallback<GeneralResponse<GetDepResp>>() {
            @Override
            public void onResponse(Call<GeneralResponse<GetDepResp>> call, Response<GeneralResponse<GetDepResp>> response) {
                if (!response.isSuccessful())
                    return;
                GeneralResponse<GetDepResp> resp = response.body();
                GetDepResp getDepResp = resp.data;
                List<Department> deps = getDepResp.departments;
                mCurrentDepCount += deps.size();
                parentDep.subDeps = deps;
                for (Department dep : deps)
                    getDepartments(dep.id, dep);
                if (mCurrentDepCount == mAllDepCounts)
                    m.setAllDeps(mRootDep.subDeps);
            }

            @Override
            public void onFailure(Call<GeneralResponse<GetDepResp>> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    @Override
    public void onValidationSucceeded() {
        mIsPass = true;
    }

    @Override
    public void onValidationFailed(List<ValidationError> errors) {
        String msg = errors.get(0).getCollatedErrorMessage(m.mContext);
        MyToast.showBlueCircleToast(m.mContext, msg);
        mIsPass = false;
    }
}
